import { Spin} from 'antd';
import {WeaSwitch} from 'comsMobx';
import { WeaTools, WeaAlertPage, WeaFormItem, WeaLocaleProvider, WeaSearchGroup } from 'ecCom';
import moment from "moment"

const getLabel = WeaLocaleProvider.getLabel;
/**
 * 获取浏览器参数
 */
export const getParams = key => {
    var href = window.location.href.replace(/&#38;/g,"&");
  　var reg = new RegExp("(^|\\?|&)"+ key +"=([^&]*)(\\s|&|$)", "i");
　　if (reg.test(href))
　　return unescape(RegExp.$2.replace(/\+/g, " "));
　　return "";
}
//匹配是否已某个字符开头 str字符串 dim判定的某个字符
export const startWith = (str, dim) => {
  var reg = new RegExp("^" + dim);
  return reg.test(str);
}
export const endWith = (str, dim) => {
  var reg = new RegExp(dim + "$");
  return reg.test(str);
}
export const transfStr = (name = '', ids = '', list = [], type = '',relateId='',model='') => {
    let str = '';
    list.map(item => {
        if (name === 'Upload' && type === 'image') {
            str += '<img class="formImgPlay" src="' + item.imgSrc + '" data-imgsrc="' + (item.loadlink || item.acclink) + '" />&#8203;';
        }
        if (name === 'Upload' && type === 'file') {
            str += `<a href='javascript:void(0)' onclick='try{openDoc(${item.fileid},${relateId},${model},this);return false;}catch(e){}' ondblclick='return false;' unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.filename}</a>
            &nbsp;<a href='javascript:void(0)' onclick='try{downloadFile(${item.fileid},${item.imagefileid},${relateId},${model},this);return false;}catch(e){}' unselectable='off' target='_blank' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${getLabel(258,'下载')}(${item.filesize})</a></br>`;
        }
        if (name === 'Browser') {
          str += `<a href='javascript:void(0)' onclick='try{openAppLink(this,${item.id},${type},${relateId},${model});return false;}catch(e){}' ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;`
        }
    })
    return str;
  }
//判断两个日期相差天数
export const DateDiffDays =(startdate,enddate)=>{
    var arr = startdate.split("-");
    var starttime = new Date(arr[0], arr[1]-1, arr[2]);
    var starttimes = starttime.getTime();
    var arrs = enddate.split("-");
    var lktime = new Date(arrs[0], arrs[1]-1, arrs[2]);
    var lktimes = lktime.getTime();
    var days = (lktimes - starttimes)/(3600*1000*24);
    return days;
}
//对比第一个字符串和（第二个数组或字符串） 找出第二个字符中删除或者第二字数组中新增的元素
export const ArrayDiffer =(str,arry,type)=>{
    if(type==1 && str.length>0){//删除
        if(arry.length==0){
            return str;
        }else{
            let res = "";
            let strArray = str.split(",");
            for(let i=0;i<strArray.length;i++){
                if(strArray[i]!="" && arry.indexOf(','+strArray[i]+',')==-1){
                    res+=strArray[i]+",";
                }
            }
            return res;
        }
    }else if(type==2 && arry.length>0){//新增
       if(str.length==0){
          return arry.toString();
       }else{
        let res = "";
        for(let i=0;i<arry.length;i++){
            if(arry[i]!="" && str.indexOf(','+arry[i]+',')==-1){
                res+=arry[i]+",";
            }
        }
        return res;
       }
    }
    return "";
}
// 页面加载中效果处理
export const renderLoading = (loading,ecId) => (
  <div style={{height: window.innerHeight}}>
    <div className="wea-demo-loading" style={{top:"40%",textAlign:"center",position:"relative"}}>
      <Spin ecId={`${ecId}_Spin@sprnqa`} spinning={loading} />
    </div>
  </div>
)
  
export const renderAlertPage = (msg,iconName,top,_height,ecId) => (
     <div style={{height: (_height?_height:window.innerHeight)}}>
    <WeaAlertPage ecId={`${ecId}_WeaAlertPage@b2ctq1`} icon={iconName?iconName:""} top={top?top:""}>
     <div dangerouslySetInnerHTML={{ __html:msg}}></div>
    </WeaAlertPage>
  </div>
)

//判空处理
export const isEmpty = (obj) => {
  if (typeof obj === 'undefined' || obj == null || obj === '') {
    return true;
  } else {
    return false;
  }
}

export const isBlank = (obj) => {
    if (typeof obj === 'undefined' || obj == null || obj === '') {
        return true;
    } else {
        obj = obj.trim()
        if (obj == '') {
            return true;
        }
        return false;
    }
}

//获取当前日期时间
export const getNowFormatDate = () => {
    let date = new Date();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    let seconds = date.getSeconds()
    if(seconds < 10){
        seconds = "0" + seconds;
    }
    let currentDate = date.getFullYear() + "-" + month + "-" + strDate
            + " " + date.getHours() + ":" + date.getMinutes() + ":" + seconds;
    return currentDate;
}

//获取当前日期
export const getNowDate = () => {
    let date = new Date();
     let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    let currentDate = date.getFullYear() + "-" + month + "-" + strDate;
    return currentDate;
}

//获取当前是时间
export const getNowTime = () => {
    let date = new Date();
    let seconds = date.getSeconds()
    let minutes = date.getMinutes();
    if(seconds < 10){
        seconds = "0" + seconds;
    }
    if(minutes < 10){
        minutes = "0" + minutes;
    }
    return date.getHours() + ":" +minutes + ":" + seconds;
}
 //下载附件
 export const downloads = (fileid) => {
    window.open("/weaver/weaver.file.FileDownload?fileid=" + fileid+"&download=1")
}
export const opendoc = (showid) => {
    window.open("/spa/document/index.jsp?id=" + showid + "#/main/document/detail"); //E9
}
let formParams = {};
// 渲染form表单: 一般对form的渲染都统一使用该方法
export const getSearchs = (form, condition, col, isCenter,onEnterSearch,ecId,filename) => {
    const {isFormInit} = form;
    const formParamstemp = form.getFormParams();
    for(let param in formParamstemp){
        formParams[param] = formParamstemp[param]
    }
    let group = [];
    isFormInit && condition && condition.map((c,idex)=> {
        let items = [];
        c.items.map((fields,idx) => {
            // if (onEnterSearch && typeof onEnterSearch === 'function' && fields.conditionType === 'INPUT') {
            //     fields.onPressEnter = onEnterSearch;
            // }
            items.push({
                com: (
                    <WeaFormItem ecId={`${ecId || ''}_WeaFormItem@3bjn2j@${filename+idx}`}
                        label={`${fields.label}`} // label 标签的文本
                        labelCol={{span: `${fields.labelcol}`}} // label标签占一行比例
                        wrapperCol={{span: `${fields.fieldcol}`}} // 右侧控件占一行比例
                        error={form.getError(fields)} // 错误提示: 处理表单中有必填项,保存的校验
                        tipPosition="bottom" // 错误提示的显示位置: top/bottom
                    >
                        <WeaSwitch ecId={`${ecId || ''}_WeaSwitch@v0vgt4@${filename+idx}`}
                            fieldConfig={fields}
                            form={form}
                            formParams={formParams}
                            onEnterSearch = {onEnterSearch}
                        />
                    </WeaFormItem>),
                colSpan: 1,
            })
        });
        group.push(
            <WeaSearchGroup ecId={`${ecId || ''}_WeaSearchGroup@xtk90o@${filename+idex}`}
                col={col || 1} // 高级搜索列布局列数
                needTigger={true} // 是否开启收缩
                title={c.title || ''} // 高级搜索标题
                showGroup={c.defaultshow} // 是否开启面板
                items={items} // 条目数组数据
                center={isCenter || false} // 内容是否居中：一般弹框需要
            />)
    });
    return group;
}
//将id和名称转成数组
export const idsAndNamesToArr = (ids, names) => {
    if (ids != undefined && names != undefined) {
        let id = ids.split(",");
        let name = names.split(",");
        let arr = [];
        for (let i = 0; i < id.length; i++) {
            arr.push({ id: id[i], name: name[i] });
        }
        return arr;
    } else {
        return [];
    }
}
 //时间转换成string
 export const convertTimeToString = (date) =>{
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    let currentDate = date.getFullYear() + "-" + month + "-" + strDate;
    return currentDate;
}

//计算结束日期
export const computeEndDate = (period) =>{
    let date = new Date()
    let y = date.getFullYear()
    let m = date.getMonth();
    if(period == "1"){
        return convertTimeToString(new Date(y,m+1,0))
    }else if(period == "2"){
        if(m>=0 && m < 3){
            return convertTimeToString(new Date(y,3,0))
        }else if(m >= 3 && m < 6){
            return convertTimeToString(new Date(y,6,0))
        }else if(m >= 6 && m < 9){
            return convertTimeToString(new Date(y,9,0))
        }else{
            return convertTimeToString(new Date(y,12,0))
        }
    }else if(period == "3"){
        return convertTimeToString(new Date(y+1,0,0))
    }else if(period == "4"){
        return convertTimeToString(new Date(y+4,0,0))
    }else if(period == "5"){
        return convertTimeToString(new Date(y+6,0,0))
    }        
}
//重新设置window.tabKeys
export const setWindowKeys =(_key,_name)=>{
    window.tabKeys = [];
    window.tabKeys.push("_key:"+_key+"_name:"+_name);
}
//得到E9顶部高度
export const getHeaderObjectHeight =()=>{
    let header = document.getElementById("themeLayoutRoute");
    let h = 0;
    if(header){
        h = $("#themeLayoutRoute").offset().top || 0;
    }
    return h;
}
//得到窗口高度
export const getCurrentHeight =()=>{
    let header =  document.getElementById("themeLayoutRoute");
    let h = 0;
    if(header){
        h = $("#themeLayoutRoute").offset().top || 0;
    }
    return window.innerHeight-h;
}
export const getCurrentWidth = ()=> {
    let header =  document.getElementById("themeLayoutRoute");
    let w = 0;
    if(header){
        w = $("#themeLayoutRoute").offset().left || 0;
    }
    return window.innerWidth-w;
}
 //获取当前周
 export const  getWeekOfYear = () => {
var today = new Date ();
var firstDay = new Date (today.getFullYear (), 0, 1);
var dayOfWeek = firstDay.getDay ();
var spendDay = 1;
if (dayOfWeek != 0) {
    spendDay = 7 - dayOfWeek + 1;
}
firstDay = new Date (today.getFullYear (), 0, 1 + spendDay);
var d = Math.ceil ((today.valueOf () - firstDay.valueOf ()) / 86400000);
var result = Math.ceil (d / 7);
if(result<2)return 1
return result-1 ;
}

//移除数组中的对象,传入数据必须含有id
export const removeAarry = (_arr,_obj) =>{
    var length = _arr.length;
    for (var i = 0; i < length; i++) {
        if (_arr[i].id == _obj.id) {
            if (i == 0) {
                _arr.shift(); //删除并返回数组的第一个元素
                return _arr;
            }
            else if (i == length - 1) {
                _arr.pop();  //删除并返回数组的最后一个元素
                return _arr;
            }
            else {
                _arr.splice(i, 1); //删除下标为i的元素
                return _arr;
            }
        }
    }
} 

//操作字符串前后的符号
export const operateSymbol = (str,symbol,operate) =>{
    if(operate == "del"){
        if(startWith(str, symbol)){
            str = str.substring(1)
        }
        if(endWith(str,symbol)){
            str = str.substring(0,str.length-1)
        }
    }else if(operate == "add"){
        if(!startWith(str, symbol)){
            str = "," + str
        }
        if(!endWith(str,symbol)){
            str = str + ","
        }
    }
    return str;
}
//得到已选中checkbox的id值字符串
export const getDataListIds = (dlist,isdel,sorttype) =>{
    let checkids = "";
    dlist && dlist.length>0 && dlist.map((element,idx)=>{
        if(element.ischeckbox==1){
            if(isdel){
                if(element.candelete){
                    checkids +=","+element.key;
                }
            }else{
                checkids +=","+element.key;
            }
        }
        if(sorttype==4){
            checkids +=getDataListIds(element.childs,isdel,sorttype);
        }
    })
    return checkids;
}
//判断当前数组是否有数据被选中
export const isSelectCheckBox = (datalist,v) =>{
    let isSelect = false;
    if(datalist && datalist.length>0 ){
        for(let i=0;i<datalist.length;i++){
            let element = datalist[i];
            if(element.ischeckbox==1){
                isSelect = true;
                return isSelect;
            }
            if(element.childs && element.childs.length>0){
                isSelect = isSelectCheckBox(element.childs,v);
                if(isSelect){
                    return isSelect;
                }
            }
        }
    }
    return isSelect;
}
//判断当前数组是否全部选中或全部未选   datalist-数组  v-0:全选 1：未选  currentid-分类id
export const isAllSelectCheckBox = (datalist,v,currentid) =>{
    let isSelect = true;
    if(datalist && datalist.length>0){
        for(let i=0;i<datalist.length;i++){
            let element = datalist[i];
            if(currentid && currentid!=""){
                if(element.treetype!="m"+currentid){
                    continue;
                }
            }
            if(element.ischeckbox==v){
                isSelect = false;
                return isSelect;
            }
            if(element.childs && element.childs.length>0){
                isSelect = isAllSelectCheckBox(element.childs,v);
                if(!isSelect){
                    return isSelect;
                }
            }
        }
    }
    return isSelect;
}
//设置数组数组checkbox框的值
export const setDataCheckBoxValue = (dlist,v,currentid,sorttype,dropSelectedKey)=>{
    dlist && dlist.length>0 && dlist.map((element,idx)=>{
        if(currentid && currentid!=""){
            if(element.treetype=="m"+currentid){
                if(dropSelectedKey==1){
                    if(element.candelete){
                        element.ischeckbox = v;
                    }else{
                        element.ischeckbox = "0";
                    }
                }else{
                    element.ischeckbox = v;
                }
            }
        }else{
            if(dropSelectedKey==1){
                if(element.candelete){
                    element.ischeckbox = v;
                }else{
                    element.ischeckbox = "0";
                }
            }else{
                element.ischeckbox = v;
            }
        }
        if(sorttype==4){
            setDataCheckBoxValue(element.childs,v,currentid,sorttype,dropSelectedKey);
        }
    })
}

/**
 * 获取N天内的两个时间段
 * @param {} count 
 * ["2020-06-16", "2020-07-16"] 
 */
export const  getDateRangeInDays = (count) =>{
    // 拼接时间
    const time1 = new Date()
    const time2 = new Date()
    if (count === 1) {
        time1.setTime(time1.getTime() - (24 * 60 * 60 * 1000))
    } else {
        if (count >= 0) {
            time1.setTime(time1.getTime())
        } else {
            if (count === -2) {
                time1.setTime(time1.getTime() + (24 * 60 * 60 * 1000) * 2)
            } else {
                time1.setTime(time1.getTime() + (24 * 60 * 60 * 1000))
            }
        }
    }
    const Y1 = time1.getFullYear()
    const M1 = ((time1.getMonth() + 1) > 9 ? (time1.getMonth() + 1) : '0' + (time1.getMonth() + 1))
    const D1 = (time1.getDate() > 9 ? time1.getDate() : '0' + time1.getDate())
    const timer1 = Y1 + '-' + M1 + '-' + D1 ;//' ' + '23:59:59' // 当前时间

    time2.setTime(time2.getTime() - (24 * 60 * 60 * 1000 * count))
    const Y2 = time2.getFullYear()
    const M2 = ((time2.getMonth() + 1) > 9 ? (time2.getMonth() + 1) : '0' + (time2.getMonth() + 1))
    const D2 = (time2.getDate() > 9 ? time2.getDate() : '0' + time2.getDate())
    const timer2 = Y2 + '-' + M2 + '-' + D2 ;//' ' + '00:00:00' // 之前的7天或者30天
    return [timer2, timer1]
}

export const getRandom = (start, end, fixed = 0)=> {
    let differ = end - start;
    let random = Math.random();
    return (start + differ * random).toFixed(fixed);
}

/**
 * 获取前一天的日期字符串
 */
export const getLastDateStr = () => {
    return moment().subtract(1, 'days').format("YYYY-MM-DD")
}